package top.lingkang.finalgateway.admin.controller;

import org.noear.snack.ONode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import top.lingkang.finalgateway.admin.constants.LogType;
import top.lingkang.finalgateway.admin.dto.ResponseResult;
import top.lingkang.finalgateway.admin.mapper.ActionLogMapper;
import top.lingkang.finalgateway.admin.param.LoginParam;
import top.lingkang.finalsecurity.solonplugin.FinalSecurityHolder;
import top.lingkang.finalvalidated.core.ValidObject;

/**
 * @author lingkang
 * @create by 2024/5/14 16:55
 */
@Controller
@Mapping("/api/user")
public class UserController {
    @Inject("${admin.username}")
    private String username;
    @Inject("${admin.password}")
    private String password;

    @Inject
    private ActionLogMapper actionLogMapper;
    @Inject
    private FinalSecurityHolder finalSecurityHolder;

    @Mapping(value = "/login", method = MethodType.POST)
    public Object loginPOST(@ValidObject LoginParam param, Context context) {
        if (param.getUsername().equals(username) &&
                param.getPassword().equals(password)) {
            actionLogMapper.addLog(LogType.user_login, ONode.load(param).toJson());
            finalSecurityHolder.login("admin", new String[0]);
            return new ResponseResult<>().ok("登录成功").setData(context.sessionState().sessionId());
        }

        return new ResponseResult<>().fail("账号或密码错误");
    }

    @Mapping("/logout")
    public Object logout(Context context) {
        String username = finalSecurityHolder.getUsername();
        context.sessionClear();
        actionLogMapper.addLog(LogType.user_logout, username);
        return new ResponseResult<>().ok();
    }

    @Mapping(value = "/isLogin", method = MethodType.GET)
    public Object isLogin() {
        return "ok";
    }
}
